package controller;

import gson.Questions;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.gson.Gson;
import com.mongodb.DBObject;

@SuppressWarnings("serial")
public class SpinServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setContentType("text/html");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.getWriter().println("<script>window.location='http://hatforrent.com/login'</script>");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		response.setCharacterEncoding("utf-8");
		String sitemap = request.getParameter("sitemap");
		String reglink = request.getParameter("reglink");
		String regtitle = request.getParameter("regtitle");
		String regcontent = request.getParameter("regcontent");
		String regremove = request.getParameter("regremove");
		String type = request.getParameter("type");
		String tag = request.getParameter("tag");
		String rewriter_title = request.getParameter("rewriter_title");
		
		sitemap = Utils.fomatSitemap(sitemap);
		
		String charset="UTF-8";
		//
		Document doc = null;
		
		ArrayList<String> site = Utils.getStachSite();
		
		
		String link="";
		try {
			if(type.equals("html"))
			{
				if(site.contains(Utils.fomatDmain(sitemap)))
				{
					String str = Utils.GetHtml("https://api.stackexchange.com/2.1/search/advanced?order=desc&answers=1&sort=activity&tagged="+tag+"&site="+Utils.fomatDmain(sitemap)+"&filter=!T5TVZso8yZqn*VSo%29T&key=vxwi93Z)iv36250wzn6aVA((", "utf-8");
					
					Gson gson = new Gson();
					
					Questions question = gson.fromJson(str, Questions.class);
					link = question.items.get(0).getLink();
				} else {
					doc = Jsoup.parse(Utils.GetHtml(sitemap, charset));
					
					String[] arrreglink = reglink.split("\\|");
					if(arrreglink.length>=2)
						link = doc.select(arrreglink[0]).get(Integer.parseInt(arrreglink[1])).attr("href");
					else
						link = doc.select(reglink).get(0).attr("href");
				}
			}
			else
			{
				try {
					doc = Jsoup.parse(Utils.GetHtml(sitemap, charset).replaceAll("<link>", "<links>").replaceAll("</link>", "</links>"));
					link = doc.select("item").get(0).select("links").get(0).text();
				} catch (Exception e) {
					link = doc.select("entry link").attr("href");
				}
			}
			
			link=Utils.fomatLink(link, sitemap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String strContent="";
		String ti = "";
		if(!link.equals(""))
		{
			if(site.contains(Utils.fomatDmain(sitemap)))
			{
				doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+link, charset));
			} else {
				doc = Jsoup.parse(Utils.GetHtml(link, charset));
			}
			
			int index = doc.select("meta").toString().toLowerCase()
					.indexOf("charset=");
			if (index != -1) {
				charset = doc.select("meta").toString().substring(index + 8)
						.replaceAll("[^\\'\\\"0-9a-zA-Z\\-\\_]+[\\w\\W]+", "")
						.replaceAll("[\\'\\\"]+", "");
			}
			//
			if(site.contains(Utils.fomatDmain(sitemap)))
			{
				doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+link, charset));
			} else {
				doc = Jsoup.parse(Utils.GetHtml(link, charset));
			}
			
			ti = doc.select(regtitle).text();
			doc = Jsoup.parse(doc.select(regcontent).html());
			String[] remove = regremove.split(" ");
			doc.select("script").remove();
			if (remove.length > 0) {
				for (int i = 0; i < remove.length; i++) {
					try {
						if ((remove[i] != null) && (!remove[i].equals("")))
						{
							String[] reg = remove[i].split("\\|"); 
							
							if(reg.length >=2)
							{
								if(reg[1].equals("last"))
								{
									doc.select(reg[0].replaceAll(">", " ")).last().remove();
								} else {
									doc.select(reg[0].replaceAll(">", " ")).first().remove();
								}
							} else {
								doc.select(remove[i].replaceAll(">", " ")).remove();
							}
						}
					} catch (Exception localException1) {
					}
				}
			}
			
			doc.select("a").attr("rel","nofollow");
			strContent = doc.html();
		}
		strContent = strContent.replaceAll("&amp;", "&");
		try {
			Elements img = doc.select("img");
			for(int i=0;i<img.size();i++)
			{
				String im= img.eq(i).attr("src");
				if(!"".equals(im))
				{
					String imageUrl = Utils.fomatLink(im, sitemap);
					
					strContent = strContent.replace(im, imageUrl);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			Elements a = doc.select("a");
			for(int i=0;i<a.size();i++)
			{
				String aa= a.eq(i).attr("href");
				if(!"".equals(aa))
				{
					String imageUrl = Utils.fomatLink(aa, sitemap);
					
					strContent = strContent.replace(aa, imageUrl);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		if("yes".equals(rewriter_title))
		{
			ti = Utils.Spin(ti);
		}
		
		request.setAttribute("str", link);
		request.setAttribute("title", ti);
		request.setAttribute("content", Utils.cleanContent(strContent));
		
		try {
			request.getRequestDispatcher("/check_link.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
